package com.example.download2;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import android.app.Notification;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.util.Log;
import android.view.View;
import android.widget.RemoteViews;

public class Download extends AsyncTask<String, Integer, Integer>{
	
	private int key;
	private int size;
	private Context mContext;
	NotyManager no;
	int id;
	public Download(Context context,NotyManager no,int id) {
		mContext=context;
		this.no=no;
		this.id=id;
	}

	@Override
	protected void onPreExecute() {
		super.onPreExecute();
	}
	@Override
	protected Integer doInBackground(String... params) {
		try {
			
			URL url = new URL(params[0]);
			HttpURLConnection con = (HttpURLConnection) url
					.openConnection();
			con.setReadTimeout(10000);
			
			/*FileOutputStream fos = mContext.openFileOutput(
					AppConstans.FILE_UPDATE, Context.MODE_WORLD_READABLE
							| Context.MODE_WORLD_WRITEABLE);*/
			InputStream is = con.getInputStream();
			FileOutputStream fos=new FileOutputStream(params[1]);
			size=con.getContentLength();
			byte[] b = new byte[1024];
			int length;
			int temp=0;
			
			while ((length = is.read(b)) != -1) {
				temp+=length;
				fos.write(b, 0, length);
				publishProgress(temp*100/size);
				notify(id,size, temp);
				
			}
			fos.flush();
			is.close();
			fos.close();

			key = AppConstans.DOWNLOAD_SUCCESS;

		} catch (MalformedURLException e) {
			e.printStackTrace();
			key = AppConstans.DOWNLOAD_ERROR;
		} catch (IOException e) {
			e.printStackTrace();
			key = AppConstans.DOWNLOAD_ERROR;
		}
		return key;
	}

	@Override
	protected void onProgressUpdate(Integer... values) {
		super.onProgressUpdate(values);
	}

	@Override
	protected void onPostExecute(Integer result) {
		super.onPostExecute(result);
		int value=result; 
		if(value==AppConstans.DOWNLOAD_SUCCESS)
		{
		}
		else
		{
			
		}
	}
	
	public void notify(int id,int totalsize,int currentSize)
	{
		Notification n=new Notification();
		n.icon=android.R.drawable.stat_sys_download;
		n.flags|=Notification.FLAG_ONGOING_EVENT;
		
		 // Build the RemoteView object
        RemoteViews expandedView = new RemoteViews(mContext.getPackageName(),
                R.layout.status_bar_ongoing_event_progress_bar);
            expandedView.setTextViewText(R.id.description,
                    "download des");
        expandedView.setTextViewText(R.id.title, "download title");

            expandedView.setViewVisibility(R.id.paused_text, View.GONE);
            expandedView.setProgressBar(R.id.progress_bar,
                    (int) totalsize,
                    (int) currentSize,
                    totalsize == -1);
        expandedView.setTextViewText(R.id.progress_text,
                getDownloadingText(totalsize,currentSize));
        expandedView.setImageViewResource(R.id.appIcon, R.drawable.ic_launcher);
        n.contentView = expandedView;
        
        /*Intent intent = new Intent(Constants.ACTION_LIST);
        intent.setClassName(mContext.getPackageName(),
                DownloadReceiver.class.getName());
        intent.setData(
                ContentUris.withAppendedId(Downloads.ALL_DOWNLOADS_CONTENT_URI, item.mId));
        intent.putExtra("multiple", item.mTitleCount > 1);*/
        Intent intent=new Intent(mContext,DownloadReceiver.class);

        n.contentIntent = PendingIntent.getBroadcast(mContext, 0, intent, 0);
        Log.e("DownloadNotification", "notify");
       // mSystemFacade.postNotification(item.mId, n);
        no.noty(id,n);
	}
	
	 /*
     * Helper function to build the downloading text.
     */
    private String getDownloadingText(long totalBytes, long currentBytes) {
        if (totalBytes <= 0) {
            return "";
        }
        long progress = currentBytes * 100 / totalBytes;
        StringBuilder sb = new StringBuilder();
        sb.append(progress);
        sb.append('%');
        return sb.toString();
    }

}
